package com.lihua.project.system.article.controller;

import java.util.Date;
import java.util.List;
import java.util.Set;

import com.lihua.common.utils.RedisUtils;
import com.lihua.project.system.comment.service.ICommentService;
import com.lihua.project.system.user.domain.User;
import com.lihua.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lihua.framework.aspectj.lang.annotation.Log;
import com.lihua.framework.aspectj.lang.enums.BusinessType;
import com.lihua.project.system.article.domain.Article;
import com.lihua.project.system.article.service.IArticleService;
import com.lihua.framework.web.controller.BaseController;
import com.lihua.framework.web.domain.AjaxResult;
import com.lihua.common.utils.poi.ExcelUtil;
import com.lihua.framework.web.page.TableDataInfo;

/**
 * 文章帖子Controller
 * 
 * @author lihua
 * @date 2022-03-27
 */
@Controller
@RequestMapping("/system/article")
public class ArticleController extends BaseController {
    private String prefix = "system/article";

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IUserService userService;

    @RequiresPermissions("system:article:view")
    @GetMapping()
    public String article()
    {
        return prefix + "/article";
    }


    @GetMapping("/index")
    public String articleIndex()
    {
        return prefix + "/article-index";
    }

    @Autowired
    private RedisUtils redisUtils;



    /**
     * 查询文章帖子列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Article article)
    {
        startPage();
        List<Article> list = articleService.selectArticleList(article);
        return getDataTable(list);
    }

    /**
     * 根据用户Id查询文章帖子列表
     */
    @PostMapping("/user/list")
    @ResponseBody
    public TableDataInfo listByUserId(Article article)
    {
        //如果userId为null，默认查询用户自己的数据
        if (article.getUserId()==null){
            User user = getSysUser();
            article.setUserId(user.getUserId());
        }
        startPage();
        List<Article> list = articleService.selectArticleList(article);
        return getDataTable(list);
    }

    /**
     * 导出文章帖子列表
     */
    @RequiresPermissions("system:article:export")
    @Log(title = "文章帖子", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Article article)
    {
        List<Article> list = articleService.selectArticleList(article);
        ExcelUtil<Article> util = new ExcelUtil<Article>(Article.class);
        return util.exportExcel(list, "文章帖子数据");
    }

    /**
     * 新增文章帖子
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 首页新增文章帖子
     */
    @GetMapping("/addIndex")
    public String addIndex(ModelMap mmap) {
        User user = getSysUser();
        mmap.put("selfUser", user);
        return prefix + "/index-add";
    }

    /**
     * 新增保存文章帖子
     */
    @RequiresPermissions("system:article:add")
    @Log(title = "文章帖子", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Article article) {
        return toAjax(articleService.insertArticle(article));
    }

    /**
     * 修改文章帖子
     */
    @RequiresPermissions("system:article:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Article article = articleService.selectArticleById(id);
        mmap.put("article", article);
        return prefix + "/edit";
    }

    /**
     * 修改保存文章帖子
     */
    @RequiresPermissions("system:article:edit")
    @Log(title = "文章帖子", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Article article)
    {
        //修改任务更新时间
        article.setUpdateTime(new Date());
        return toAjax(articleService.updateArticle(article));
    }

    /**
     * 删除文章帖子
     */
    @RequiresPermissions("system:article:remove")
    @Log(title = "文章帖子", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(articleService.deleteArticleByIds(ids));
    }


    /**
     * 查询详细方法
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        User user = getSysUser();
        //用于判断用户是否登录
        mmap.put("user", user);
        Article article = articleService.selectArticleById(id);
        mmap.put("article",article);
        //发布文章的用户
        Long userId = article.getUserId();
        User publish = userService.selectUserById(userId);
        mmap.put("publish",publish);

        //统计阅读量
        String redisKey = "article-flow-"+id;
        String redisValue = (String)redisUtils.get(redisKey);
        if (redisValue==null){
            String articleFlow = redisKey+":"+1;
            redisValue = articleFlow;
            redisUtils.set(redisKey,articleFlow);
        } else {
            String viewNum = redisValue.replace(redisKey + ":", "");
            String articleFlow = redisKey+":"+(Long.parseLong(viewNum)+1);
            redisUtils.set(redisKey,articleFlow);
        }


        //如果文章范围多，那么将文章，插入热榜。（插入逻辑，10天内，访问量达到50）
        String hotListKey = "article-hot-list-id";
        if (article.getArticleNewstime().getTime()+86400000*3>System.currentTimeMillis()){
            //3天内
            long viewNum = Long.parseLong(redisValue.replace(redisKey + ":", ""));
            if (viewNum>1){
                //浏览量大于50 ,插入热榜。
                redisUtils.addZset(hotListKey,article.getId(),viewNum);
            }
        }
        return prefix + "/detail";
    }
}
